package view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import utils.ValidateFormTools;
import model.bean.Project;
import model.dao.ProjectDAO;

public class PnlAdminProjectManage extends JPanel {

	 DefaultTableModel tblModel;
	    List<Project> projectList;
	    // Variables declaration - do not modify//GEN-BEGIN:variables
	    private JButton 	btnAddNew;
	    private JButton 	btnDelete;
	    private JButton 	btnUpdate;
	    private JLabel 		jLabel1;
	    private JLabel 		jLabel2;
	    private JLabel 		jLabel3;
	    private JLabel 		jLabel4;
	    private JPanel 		pnlAddNew;
	    private JPanel 		pnlBottom;
	    private JPanel 		pnlEdit;
	    private JPanel 		pnlTop;
	    private JScrollPane	sclPaneData;
	    private JScrollPane sclPaneData1;
	    private JTable 		tblData;
	    private JTextField 	tfAddNewProjectID;
	    private JTextField 	tfAddNewProjectName;
	    private JTextField 	tfEditProjectID;
	    private JTextField 	tfEditProjectName;
	    // End of variables declaration//GEN-END:variables
	    /** Creates new form ProjectUIPanel */
	    public PnlAdminProjectManage() {
	        initComponents();
	        tblModel = new DefaultTableModel();
	      
	        loadTableData();
	    }

	    private void initComponents() {

	        pnlTop 				= new JPanel();
	        pnlAddNew 			= new JPanel();
	        jLabel1 			= new JLabel();
	        tfAddNewProjectID 	= new JTextField();
	        jLabel2 			= new JLabel();
	        tfAddNewProjectName = new JTextField();
	        btnAddNew 			= new JButton();
	        pnlEdit 			= new JPanel();
	        jLabel4 			= new JLabel();
	        jLabel3 			= new JLabel();
	        tfEditProjectID 	= new JTextField();
	        tfEditProjectName	= new JTextField();
	        btnUpdate 			= new JButton();
	        btnDelete 			= new JButton();
	        pnlBottom 			= new JPanel();
	        sclPaneData 		= new JScrollPane();
	        sclPaneData1 		= new JScrollPane();
	        tblData 			= new JTable();

	        setMaximumSize(new Dimension(791, 655));
	        setMinimumSize(new Dimension(791, 655));
	        setPreferredSize(new Dimension(791, 655));
	        setLayout(new BorderLayout());

	        pnlTop.setPreferredSize(new Dimension(671, 160));
	        pnlTop.setRequestFocusEnabled(false);
	        pnlTop.setLayout(new BorderLayout());

	        pnlAddNew.setBorder(BorderFactory.createTitledBorder(null, "Add new project", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new java.awt.Font("Calibri", 1, 12))); // NOI18N
	        pnlAddNew.setPreferredSize(new Dimension(671, 80));

	        jLabel1.setText("Project id");

	        tfAddNewProjectID.setEditable(false);
	        tfAddNewProjectID.setEnabled(false);

	        jLabel2.setText("Project name");

	        btnAddNew.setIcon(new ImageIcon(getClass().getResource("/images/btn_add.png"))); 
	        btnAddNew.setText("Add");
	        btnAddNew.addActionListener(new ActionListener() {
	            public void actionPerformed(ActionEvent evt) {
	                btnAddNewActionPerformed(evt);
	            }
	        });

	        GroupLayout pnlAddNewLayout = new GroupLayout(pnlAddNew);
	        pnlAddNew.setLayout(pnlAddNewLayout);
	        pnlAddNewLayout.setHorizontalGroup(
	            pnlAddNewLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
	            .addGroup(pnlAddNewLayout.createSequentialGroup()
	                .addContainerGap()
	                .addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(ComponentPlacement.UNRELATED)
	                .addComponent(tfAddNewProjectID, GroupLayout.PREFERRED_SIZE, 59, GroupLayout.PREFERRED_SIZE)
	                .addGap(18, 18, 18)
	                .addComponent(jLabel2, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(ComponentPlacement.UNRELATED)
	                .addComponent(tfAddNewProjectName, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE)
	                .addGap(28, 28, 28)
	                .addComponent(btnAddNew, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
	                .addContainerGap(178, Short.MAX_VALUE))
	        );
	        pnlAddNewLayout.setVerticalGroup(
	            pnlAddNewLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
	            .addGroup(pnlAddNewLayout.createSequentialGroup()
	                .addGap(11, 11, 11)
	                .addGroup(pnlAddNewLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
	                    .addComponent(jLabel1)
	                    .addComponent(tfAddNewProjectID, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                    .addComponent(jLabel2)
	                    .addComponent(tfAddNewProjectName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                    .addComponent(btnAddNew))
	                .addContainerGap(18, Short.MAX_VALUE))
	        );

	        pnlTop.add(pnlAddNew, BorderLayout.NORTH);

	        pnlEdit.setBorder(BorderFactory.createTitledBorder(null, "", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new java.awt.Font("Calibri", 1, 12))); // NOI18N
	        pnlEdit.setPreferredSize(new Dimension(671, 80));

	        jLabel4.setText("Project id");

	        jLabel3.setText("Project name");

	        tfEditProjectID.setEditable(false);
	        tfEditProjectID.setEnabled(false);

	        btnUpdate.setIcon(new ImageIcon(getClass().getResource("/images/btn_save.png"))); 
	        btnUpdate.setText("Update");
	        btnUpdate.addActionListener(new ActionListener() {
	            public void actionPerformed(ActionEvent evt) {
	                btnUpdateActionPerformed(evt);
	            }
	        });

	        btnDelete.setIcon(new ImageIcon(getClass().getResource("/images/btn_delete.png")));
	        btnDelete.setText("Delete");
	        btnDelete.addActionListener(new ActionListener() {
	            public void actionPerformed(ActionEvent evt) {
	                btnDeleteActionPerformed(evt);
	            }
	        });

	        GroupLayout pnlEditLayout = new GroupLayout(pnlEdit);
	        pnlEdit.setLayout(pnlEditLayout);
	        pnlEditLayout.setHorizontalGroup(
	            pnlEditLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
	            .addGroup(pnlEditLayout.createSequentialGroup()
	                .addContainerGap()
	                .addComponent(jLabel4, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(ComponentPlacement.UNRELATED)
	                .addComponent(tfEditProjectID, GroupLayout.PREFERRED_SIZE, 59, GroupLayout.PREFERRED_SIZE)
	                .addGap(18, 18, 18)
	                .addComponent(jLabel3, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(ComponentPlacement.UNRELATED)
	                .addComponent(tfEditProjectName, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE)
	                .addGap(28, 28, 28)
	                .addComponent(btnUpdate, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(ComponentPlacement.RELATED)
	                .addComponent(btnDelete, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
	                .addContainerGap(72, Short.MAX_VALUE))
	        );
	        pnlEditLayout.setVerticalGroup(
	            pnlEditLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
	            .addGroup(pnlEditLayout.createSequentialGroup()
	                .addContainerGap()
	                .addGroup(pnlEditLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
	                    .addComponent(jLabel4)
	                    .addComponent(tfEditProjectID, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                    .addComponent(jLabel3)
	                    .addComponent(tfEditProjectName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	                    .addComponent(btnUpdate)
	                    .addComponent(btnDelete))
	                .addContainerGap(31, Short.MAX_VALUE))
	        );

	        pnlTop.add(pnlEdit, BorderLayout.CENTER);

	        add(pnlTop, BorderLayout.NORTH);

	        pnlBottom.setBorder(BorderFactory.createTitledBorder(null, "Projectlist", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new java.awt.Font("Calibri", 1, 12))); // NOI18N
	        pnlBottom.setLayout(new BorderLayout());

	        sclPaneData.setBorder(null);

	        sclPaneData1.setBorder(null);

	        tblData.setModel(new DefaultTableModel(
	            new Object [][] {
	                {null, null, null, null},
	                {null, null, null, null},
	                {null, null, null, null},
	                {null, null, null, null}
	            },
	            new String [] {
	                "Title 1", "Title 2", "Title 3", "Title 4"
	            }
	        ));
	        tblData.addMouseListener(new MouseAdapter() {
	            public void mouseClicked(MouseEvent evt) {
	                tblDataMouseClicked(evt);
	            }
	        });
	        tblData.addKeyListener(new KeyAdapter() {
	            public void keyReleased(KeyEvent evt) {
	                tblDataKeyReleased(evt);
	            }
	        });
	        sclPaneData1.setViewportView(tblData);

	        sclPaneData.setViewportView(sclPaneData1);

	        pnlBottom.add(sclPaneData, BorderLayout.CENTER);

	        add(pnlBottom, BorderLayout.CENTER);
	    }// </editor-fold>//GEN-END:initComponents

	    private void btnAddNewActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btnAddNewActionPerformed
	        if (validateAddNew()) {
	            Project proj = new Project(tfAddNewProjectName.getText());
	            //try {
	                ProjectDAO.insertProject(proj);
	                tfAddNewProjectName.setText("");
	                loadTableData();
//	            } catch (SQLException ex) {
//	                JOptionPane.showMessageDialog(null,
//	                        "",
//	                        "",
//	                        JOptionPane.ERROR_MESSAGE);
//	                Logger.getLogger(PnlAdminProjectManage.class.getName()).log(Level.SEVERE, null, ex);
//	            } catch (ClassNotFoundException ex) {
//	                JOptionPane.showMessageDialog(null,
//	                        "",
//	                        "",
//	                        JOptionPane.ERROR_MESSAGE);
//	                Logger.getLogger(PnlAdminProjectManage.class.getName()).log(Level.SEVERE, null, ex);
//	            }
	        }
	    }//GEN-LAST:event_btnAddNewActionPerformed

	    private void tblDataKeyReleased(KeyEvent evt) {//GEN-FIRST:event_tblDataKeyReleased
	        loadEditData();
	}//GEN-LAST:event_tblDataKeyReleased

	    private void tblDataMouseClicked(MouseEvent evt) {//GEN-FIRST:event_tblDataMouseClicked
	        loadEditData();
	}//GEN-LAST:event_tblDataMouseClicked

	    private void btnUpdateActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
	        if (tblData.getSelectedRow() != -1) {
	            if (validateUpdate()) {
	                int rowI = tblData.getSelectedRow();
	                Project proj = projectList.get(rowI);
	                proj.setProjectName(tfEditProjectName.getText());
	                //try {
	                    ProjectDAO.updateProject(proj);
	                    tfEditProjectID.setText("");
	                    tfEditProjectName.setText("");
	                    loadTableData();
//	                } catch (SQLException ex) {
//	                    Logger.getLogger(PnlAdminProjectManage.class.getName()).log(Level.SEVERE, null, ex);
//	                } catch (ClassNotFoundException ex) {
//	                    Logger.getLogger(PnlAdminProjectManage.class.getName()).log(Level.SEVERE, null, ex);
//	                }
	            }
	        }
	        else {
	            JOptionPane.showMessageDialog(null, "You must select one row at under.",
	                    "not row selected", JOptionPane.INFORMATION_MESSAGE);
	        }

	    }//GEN-LAST:event_btnUpdateActionPerformed

	    private void btnDeleteActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
	        System.out.println(tblData.getSelectedRow());
	        if (tblData.getSelectedRow() != -1) {
	            if (validateDelete()) {
	                if (JOptionPane.showConfirmDialog(null,
	                        "You want to delete ?",
	                        "Comfirm",
	                        JOptionPane.OK_CANCEL_OPTION)
	                        == JOptionPane.OK_OPTION) {
	                   // try {
	                        ProjectDAO.deleteProject(Integer.parseInt(tfEditProjectID.getText()));
	                        tfEditProjectID.setText("");
	                        tfEditProjectName.setText("");
	                        loadTableData();
//	                    } catch (SQLException ex) {
//	                        JOptionPane.showMessageDialog(null,
//	                                "X",
//	                                "",
//	                                JOptionPane.ERROR_MESSAGE);
//	                    } catch (ClassNotFoundException ex) {
//	                        JOptionPane.showMessageDialog(null,
//	                                "",
//	                                "",
//	                                JOptionPane.ERROR_MESSAGE);
//	                    }
	                }

	            }
	        }
	    }//GEN-LAST:event_btnDeleteActionPerformed

	    private boolean validateAddNew()//Validate to add new Project
	    {
	        StringBuilder msg = new StringBuilder();
	        if (!ValidateFormTools.isFilledTextField(tfAddNewProjectName, true)) {
	            msg.append("\n - Project name is empty.");
	        }

	        if (msg.toString().compareTo("") != 0) {
	            JOptionPane.showMessageDialog(null,
	                    "Have some error" + msg,
	                    "new error",
	                    JOptionPane.ERROR_MESSAGE);
	            return false;
	        } else {
	            return true;
	        }
	    }

	    private boolean validateDelete() //Ensure there are no Transfer or Employee link to this Project
	    {
	        int rowI = tblData.getSelectedRow();
	        Project proj = projectList.get(rowI);

	        if (proj.getFromTransferCount() == 0 && proj.getToTransferCount() == 0 && proj.getNumberOfEmployees() == 0) {
	            return true;
	        } else {
	            JOptionPane.showMessageDialog(null,
	                    "You can not delete.",
	                    "Error",
	                    JOptionPane.ERROR_MESSAGE);
	            return false;

	        }
	    }

	    private boolean validateUpdate() //Validate to edit an Project
	    {
	        StringBuilder msg = new StringBuilder();
	        if (!ValidateFormTools.isFilledTextField(tfEditProjectName, true)) {
	            msg.append("\n - Project name is empty.");
	        }

	        if (msg.toString().compareTo("") != 0) {
	            JOptionPane.showMessageDialog(null,
	                    "Have some error" + msg,
	                    "new error",
	                    JOptionPane.ERROR_MESSAGE);
	            return false;
	        } else {
	            return true;
	        }
	    }

	    private void loadEditData()//Load data to edit form, when user click or press up/down key on table
	    {
	        if (tblData.getSelectedRow() != -1) {
	            int rowI = tblData.getSelectedRow();
	            Project proj = projectList.get(rowI);
	            tfEditProjectID.setText(String.valueOf(proj.getProjectId()));
	            tfEditProjectName.setText(String.valueOf(proj.getProjectName()));
	        }
	    }

	    private void loadTableData()//Load data from database to table
	    {
	        //try {
	            projectList = ProjectDAO.selectAllProject();
	            tblModel = new DefaultTableModel();
	            tblModel.addColumn("Project id");
	            tblModel.addColumn("Project name");
	            tblModel.addColumn("Number employees");
	           for (Project project : projectList) {
	                Vector<String> row = new Vector<String>();
	                row.addElement(String.valueOf(project.getProjectId()));
	                row.addElement(project.getProjectName());
	                row.addElement(String.valueOf(project.getNumberOfEmployees()));
	               tblModel.addRow(row);
	            }
	            tblData.setModel(tblModel);
//	        } catch (ClassNotFoundException ex) {
//	            JOptionPane.showMessageDialog(null,
//	                    "",
//	                    "",
//	                    JOptionPane.ERROR_MESSAGE);
//	            ex.printStackTrace();
//	        } catch (SQLException ex) {
//	            JOptionPane.showMessageDialog(null,
//	                     "",
//	                    "",
//	                    JOptionPane.ERROR_MESSAGE);
//	            ex.printStackTrace();
//	        }

	    }

	   
	   
	


}
